package com.lime49.lockcrypt.ui;
import java.util.ArrayList;
import javax.swing.table.AbstractTableModel;

/**
 * A model used for icons or other graphics representations. Call the constructor with the
 *  number of columns, then use tablemodel.add(whatever) to add objects. Call .complete() on 
 *  the model, then pass it as the argument to as JTable constructor: new JTable(tablemodel).
 */

public class IconTableModel extends AbstractTableModel {
    private Object[][] data;
    private ArrayList<Object> dataRaw;
    private int cols, rows;
    
    /**
    * Creates a JTable of icons table with the specified number of columns
    */
    public IconTableModel(int cols) {
        data = new Object[1][cols];
        dataRaw = new ArrayList<Object>();
        this.cols = cols;
    }
    
    /**
    * Adds an item to the list of items to display
    */
    public void add(Object iconFileName) {
        dataRaw.add(iconFileName);
    }
    
    /**
    * Marks this IconTable as complete, setting it's rows and columns from the temporary buffer of items
    */
    public void complete() {
        int numIcons = dataRaw.size();
        if(numIcons%cols == 0) {
            rows = numIcons/cols;
        } else {
            rows = (numIcons/cols)+1;
        }
        data = new Object[rows][cols];
        int row=0, col=0, c=0;
        rowloop: while(c<numIcons) {
            for(col=0;col<cols;col++) {
                if(c<numIcons) {
                    data[row][col] = dataRaw.get(c);
                    c++;
                } else {
                    break rowloop;
                }
            }
            row++;
        }
    }
    
    /**
    * Should only be called after .complete()
    * @return The number of columns in this table
    */
    public int getColumnCount() {
        if(data.length>0) {
            return data[0].length;
        } else {
            return 0;
        }
    }
    
    /**
    * Should only be called after .complete()
    * @return The number of rows in this table
    */
    public int getRowCount() {
        return data.length;
    }
    
    /**
    * Returns the location of the specified value
    * @param value The value to search for
    * @return An array containing the row at index 0 and column at index 1
    */
    public int[] getValueLocation(String value) {
        for(int row = 0;row<this.rows;row++) {
            for(int col = 0;col<this.cols;col++) {
                if(data[row][col].equals(value)){
                    return new int[] {row,col};
                }
            }
        }
        return null;
    }
    
    /**
    * Finds the value at the specified row and column
    * @param row The row number
    * @param col The column number
    * @return The value
    */
    public Object getValueAt(int row, int col) {
        return data[row][col];
    }
}